package com.asiainfo.sqlextractor.exec;

import com.alibaba.fastjson.JSON;
import com.asiainfo.sqlextractor.adapter.MemSchemaFactory;
import com.asiainfo.sqlextractor.functions.Functions;
import org.apache.calcite.linq4j.tree.Types;
import org.apache.calcite.rel.RelRoot;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.calcite.schema.impl.ScalarFunctionImpl;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.parser.SqlParseException;
import org.apache.calcite.tools.*;
import org.junit.Before;
import org.junit.Test;

import java.lang.reflect.Method;
import java.sql.PreparedStatement;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public final class SqlExtractorTest2 extends TestBase {

    private final Properties properties = new Properties();

    private final String testSQL = readText("query.sql");

    @Before
    public void setUp() {
        properties.setProperty("schemaFactory", MemSchemaFactory.class.getCanonicalName());
    }

    @Test
    public void assertSingleExecute() throws SqlParseException, ValidationException, RelConversionException {
        SchemaPlus rootSchema = Frameworks.createRootSchema(true);
        Method callApi = Types.lookupMethod(Functions.class, "callApi", String.class);
        rootSchema.add("CALL_API", ScalarFunctionImpl.create(callApi));
        final FrameworkConfig config = Frameworks.newConfigBuilder().defaultSchema(rootSchema).build();
        final Planner planner = Frameworks.getPlanner(config);
        final String sql = "select CALL_API('queryCalcMode')";
        SqlNode parse = planner.parse(sql);
        SqlNode validNode = planner.validate(parse);
        RelRoot planRoot = planner.rel(validNode);
        PreparedStatement stmt = RelRunners.run(planRoot.rel);
        List<Map<String, Object>> res = safeQueryResult(stmt);
        System.out.println(JSON.toJSONString(res));
    }

}
